<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			*{margin: 0;padding: 0;}
			ul,li{list-style: none;}
			[v-cloak]{display: none;}
			#app{width: 300px;margin: 10px auto;}
			.list>li{
				margin: 10px;
				border: 1px solid #ccc;
			}
			.add-handle{
				width: 300px;
				height: 150px;
				border: 2px solid #0000FF;
			}
			.change-handle{
				width: 300px;
				height: 150px;
				border: 2px solid #CC0000;
			}
			.active{
				background: lavender;
			}
		</style>
	</head>
	<body>
		<!--v-cloak在加载时页面不会显示源码-->
		<div id="app" v-cloak>
			<!--新增模块-->
			<div class="add-handle" v-show="flag==1">
				<input placeholder="姓名" v-model="name"/><br />
				<input type="number" placeholder="年龄" v-model="age"/><br />
				<textarea placeholder="个性签名" v-model="sign"></textarea><br />
				<button @click="addlist()">新增</button>
				<button @click="clearinput()">取消</button>
			</div>
			<!--修改模块-->
			<div class="change-handle" v-show="flag==0">
				<input placeholder="姓名" v-model="name"/><br />
				<input type="number" placeholder="年龄" v-model="age"/><br />
				<textarea placeholder="个性签名" v-model="sign"></textarea><br />
				<button @click="selectchange()">确认修改</button>
				<button @click="clearinput()">取消</button>
			</div>
			<!--列表模块-->
			<ul class="list">
				<li v-for="(item,index) in userData" :class="{active:index==sindex}" @mouseover="selectbackground(index)" @mouseout="nonebackground()">
					<h5>{{item.name}}</h5>
					<p>{{item.age}}</p>
					<h4>{{item.sign}}</h4>
					<button @click="changelist(index)">修改</button>
					<button @click="deletelist(index)">删除</button>
				</li>
			</ul>
		</div>
	</body>
</html>
<script src="vue.js"></script>
<script type="text/javascript">
	var vm = new Vue({
		el:"#app",
		data:{
			name:"",
			age:"",
			sign:"",
			userData:[],
			flag:1,
			oindex:-1,
			sindex:-1
		},
		methods:{
			addlist(){
				//在vue中要v-for历遍，可能需要声明一个obj再push到数组中
				if(this.name&&this.age){
					let obj = {
						name:this.name,
						age:this.age,
						sign:this.sign
					};
					this.userData.push(obj);
					console.log(this.userData);
					this.clearinput();
				}
			},
			clearinput(){
				this.name = "";
				this.age = "";
				this.sign = "";
				if(this.flag == 0){
					this.flag = 1;
				}
			},
			changelist(index){
				this.flag = 0;
				this.name = this.userData[index].name;
				this.age = this.userData[index].age;
				this.sign = this.userData[index].sign;
				this.oindex = index;
			},
			deletelist(index){
				//截取数组
				this.userData.splice(index,1)
			},
			selectchange(){
				this.flag = 1;
				let obj = {
					name:this.name,
					age:this.age,
					sign:this.sign
				}
				//替换数组
				this.userData.splice(this.oindex,1,obj)
				this.clearinput();
			},
			selectbackground(index){
				this.sindex = index;
			},
			nonebackground(){
				this.sindex = -1;
			}
		}
	})
</script>